<template>
	<div class="cms-site-container">
		<el-dialog title="新增站点" v-model="isShowDialog" >
			<el-form ref="addSiteFormRef" :model="formData" :rules="formRules" label-width="80px">
				<el-row :gutter="35">
					<el-col>
						<el-form-item label="LOGO" prop="logo">
							<el-upload ref="logoUploadRef" limit="1" list-type="picture-card" 
								:accept="upload.accept"
								:auto-upload="false"
								:action="upload.action"
								:headers="upload.headers"
								:name="upload.name"
								:file-list="upload.images"
								:before-upload="handleBeforeUpload"
								:on-change="handleUploadChange"
								:on-exceed="handleUploadExceed"
								:on-preview="handleUploadPreview"
								:on-success="handleUploadSuccess"
								:on-remove="handleUploadRemove">
								<el-icon><plus /></el-icon>
							</el-upload>
							<el-dialog v-model="upload.dialogVisible">
								<center>
									<el-image :src="upload.picture"/>
								</center>
							</el-dialog>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="站点名称" prop="name">
							<el-input v-model="formData.name" placeholder="请输入站点名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="站点状态" prop="status">
							<el-select v-model="formData.status" placeholder="请选择站点状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="站点排序" prop="orderNum">
							<el-input-number v-model="formData.orderNum" :min="0" :max="999" clearable class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="站点备注" prop="remark">
							<el-input type="textarea" v-model="formData.remark" placeholder="请输入站点备注" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<CropperDialog ref="cropperDialogRef" :model="cropper.options" @submit="onCropperDialogSubmit" @cancel="onCropperDialogCancel"/>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import { Plus } from '@element-plus/icons-vue';
import { addSite } from '/@/api/cms/channel/index';
import { uploadPicture } from '/@/api/cms/helper/index';
import CropperDialog from '/@/views/cms/material/cropper/index.vue';
export default {
	name: 'cms/site/add',
	components: { Plus, CropperDialog },
	setup(props, context) {
		const addSiteFormRef = ref();
		const logoUploadRef = ref();
		const cropperDialogRef = ref();
		const state = reactive({
			isShowDialog: false,
			formData: {
				parentId : 0,
				orderNum : 1
			},
			formRules : {
				name: { required: true, message: '站点名称不能为空', trigger: 'blur' },
				status: { required: true, message: '站点状态不能为空', trigger: 'change' },
			},
			upload: {
				action: uploadPicture(),
				accept: '.svg,.webp,.gif,.jpg,.png,.jpeg',
				headers: { Authorization: 'Bearer ' + Session.get('token') },
				name: 'upload',
				images: [],
				dialogVisible : false
			},
			cropper: {
				options: {
					aspectRatio: 0,
				}
			}
		});

		// 打开弹窗
		const openDialog = (row?: object) => {
			state.isShowDialog = true;
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
			state.upload.images = [];
			for(var key in state.formData) {
				state.formData[key] = undefined;
			}
			addSiteFormRef.value.resetFields();
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 新增
		const onSubmit = () => {
			addSiteFormRef.value.validate(valid => {
				if(valid){
					let params = {
						siteId: 0,
						parentId: 0,
						type: 1,
						logo: state.formData.logo,
						name: state.formData.name,
						status: state.formData.status,
						orderNum: state.formData.orderNum,
						remark: state.formData.remark
					}
					addSite(params).then((res) => {
						if(res.code === 0){
							ElMessage.success('保存成功');
							context.emit('submit');
							closeDialog();
						}
					});
				}
			});
		};
		
		//上传之前
		const handleBeforeUpload = (file) => {
			state.upload.headers.Authorization = 'Bearer ' + Session.get('token');
		}
		//文件状态改变时
		const handleUploadChange = (file) => {
			if(file.status == 'ready') {
				const ext = file.name.substring(file.name.lastIndexOf('.'));
				if(file.size > 0 && state.upload.accept.indexOf(ext) != -1){
					cropperDialogRef.value.openDialog(file);
				}else{
					ElMessage.warning('请选择' + state.upload.accept + '格式的图片');
					state.upload.images = [];
				}
			}
		}
		const handleUploadExceed = () => {
			ElMessage.warning('最多允许上传1张LOGO图片');
		}
		//上传中
		const handleUploadPreview = (file) => {
			if(file.url){
				state.upload.dialogVisible = true;
				state.upload.picture = file.url;
			}
		};
		//上传成功
		const handleUploadSuccess = (res, file) => {
			if(res.state == 'SUCCESS' && res.url){
				file.url = res.url;
				state.formData.logo = res.url;
			}
		};
		//移除
		const handleUploadRemove = (file) => {
			state.formData.logo = '';
		};
		const onCropperDialogSubmit = (file, base64) => {
			const newFile = base64ToFile(base64, file.name);
			logoUploadRef.value.handleRemove(file);
			logoUploadRef.value.handleStart(newFile);
			logoUploadRef.value.submit();
		}
		const onCropperDialogCancel = (file) => {
			logoUploadRef.value.handleRemove(file);
		}
		//将base64转换为文件
		const base64ToFile = (base64, filename) => { 
			var arr = base64.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new File([u8arr], filename, {type: mime});
		}
		return {
			addSiteFormRef,
			logoUploadRef,
			cropperDialogRef,
			openDialog,
			closeDialog,
			onCancel,
			onSubmit,
			handleBeforeUpload,
			handleUploadChange,
			handleUploadExceed,
			handleUploadPreview,
			handleUploadSuccess,
			handleUploadRemove,
			onCropperDialogSubmit,
			onCropperDialogCancel,
			...toRefs(state),
		};
	},
};
</script>